<template>
  <!-- <div class='container'>试题录入</div> -->
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span v-if="this.mallid === undefined">试题录入</span>
      <span v-else>试题修改</span>
    </div>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="学科：" prop="subjectID">
        <el-select
          v-model="form.subjectID"
          placeholder="请选择"
          style="width: 400px"
        >
          <el-option
            v-for="item in subjectList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录：" prop="catalogID">
        <el-select
          v-model="form.catalogID"
          placeholder="请选择"
          style="width: 400px"
        >
          <el-option
            v-for="item in directoryList"
            :key="item.id"
            :label="item.directoryName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业：" prop="enterpriseID">
        <el-select
          v-model="form.enterpriseID"
          placeholder="请选择"
          style="width: 400px"
        >
          <el-option
            v-for="item in enterpriseList"
            :key="item.id"
            :label="item.company"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="城市：" prop="city">
        <el-select
          v-model="form.province"
          placeholder="请选择"
          style="width: 200px"
          @change="changecity"
        >
          <el-option
            v-for="item in provincesList"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="form.city"
          placeholder="请选择"
          style="width: 200px; margin-left: 2px"
        >
          <el-option
            v-for="item in regionList"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="方向：" prop="direction">
        <el-select
          v-model="form.direction"
          placeholder="请选择"
          style="width: 400px"
        >
          <el-option
            v-for="item in directionList"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题型：" prop="questionType">
        <el-radio-group v-model="form.questionType">
          <el-radio label="1" @change="singlebtn">单选</el-radio>
          <el-radio label="2" @change="multiplebtn">多选</el-radio>
          <el-radio label="3" @change="isshowbtn">简答</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="难度：" prop="difficulty">
        <el-radio-group v-model="form.difficulty">
        <el-radio label="1" >简单</el-radio>
          <el-radio label="2" >一般</el-radio>
          <el-radio label="3" >困难</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="题干：" prop="question">
        <!-- 富文本编辑器 -->
        <quill-editor
          v-model="form.question"
          :options="editorOption"
          @blur="contentRule"
        ></quill-editor>
      </el-form-item>
      <el-form-item
        label="选项:"
        prop="options"
        v-show="isshow"
        v-if="this.isdisplay === true"
      >
        <el-radio-group v-model="isChoice" @change="handleRadio">
          <div
            class="option_item"
            v-for="item in optionsList"
            :key="item.code"
            :label="item.code"
            :value="item.code"
          >
            <el-radio style="margin-right: 10px" :label="item.code" v-model="item.code"
              >{{ item.code }}:</el-radio
            >
            <el-input
              style="width: 240px; height: 36px; margin-left: 10px"
              v-model="item.title"
            ></el-input>
            <UploadImg :img="item.img" :code="item.code" @seachimg="setImg"/>
          </div>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选项:" prop="options" v-show="isshow" v-else>
        <el-checkbox-group v-model="isCheckeds" @change="handleCheckedChange">
          <div
            class="option_item"
            v-for="item in optionsList"
            :key="item.code"
            :label="item.code"
            :value="item.code"
          >
            <el-checkbox :label="item.code" v-model="item.code">{{ item.code }}:</el-checkbox>
            <el-input
              style="width: 240px; height: 36px; margin-left: 10px"
              v-model="item.title"
            ></el-input>
            <UploadImg :img="item.img" :code="item.code" @seachimg="setcheckImg"/>
          </div>
        </el-checkbox-group>
      </el-form-item>
      <el-button
        type="danger"
        style="display: block; margin-left: 80px; margin-bottom: 20px"
        :disabled="isdisabled"
        v-show="isshow"
        @click="addformpush"
        >+增加选项与答案</el-button
      >
      <el-form-item label="解析视频:">
        <el-input
          v-model="form.videoURL"
          style="width: 400px; height: 36px"
        ></el-input>
      </el-form-item>
      <el-form-item label="答案解析: " prop="question">
        <quill-editor
          v-model="form.answer"
          :options="editorOption"
          @blur="contentRule"
        ></quill-editor>
      </el-form-item>
      <el-form-item label="题目备注:">
        <el-input
          v-model="form.remarks"
          type="textarea"
          :rows="4"
          placeholder="请输入内容"
          style="width: 400px; min-height: 33px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="试题标签:">
        <el-select
          multiple
          v-model="tagArr"
          @change="transformation"
          placeholder="请选择试题标签"
          style="width: 400px; height: 36px"
        >
          <el-option v-for="item in tagsList" :key="item.id" :value="item.tags">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-if="this.mallid === undefined"
          type="primary"
          @click="submitForm()"
          >确认提交</el-button
        >
        <el-button v-else type="success" @click="submitForm()"
          >确认修改</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
// 引入必要的COS模块
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { simple as getsubjects } from '@/api/hmmm/subjects.js'
import { list as getdirectorys } from '@/api/hmmm/directorys.js'
import { list as getenterprise } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction } from '@/api/hmmm/constants.js'
import { list, add, update, detail } from '@/api/hmmm/questions.js'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  ['blockquote', 'code-block'], // 引用 代码块-----['blockquote', 'code-block']
  ['image', 'link'] // 链接、图片、视频-----['link', 'image', 'video']
]
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      // 富文本编辑器的配置
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions
          }
        }
      },
      form: {
        number: '',
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '', // 题型
        difficulty: '', // 难度
        question: '', // 题干
        options: [
          {
            // 选项
            code: '', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        isPerfect: false
      },
      imageUrl: '',
      isshow: true,
      isdisplay: true,
      isdisabled: true,
      optionsList: [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: 0
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: 0
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: 0
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: 0
        }
      ],
      rules: {
        subjectID: [
          { required: true, message: '请选择学科名称', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请选择目录名称', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业名称', trigger: 'blur' }
        ],
        // province: [
        //   { required: true, message: '请选择城市名称', trigger: 'blur' }
        // ],
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [
          { required: true, message: '请选择方向名称', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型名称', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度名称', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请选择题干名称', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请选择答案解析名称', trigger: 'blur' }
        ]
      },
      subjectList: [], // 学科列表
      directoryList: [], // 目录列表
      enterpriseList: [], // 企业列表
      provincesList: provinces(), // 城市列表
      regionList: [], // 地区列表
      directionList: direction, // 方向列表
      tagsList: [], // tags标签列表
      tagArr: [], // tags数组
      mallid: '', // 修改id
      ASCIIlist: [], // asc列表
      isChoice: '',
      isCheckeds: [],
      percent: 0
    }
  },
  watch: {
    $route: 'getid',
    form: {
      async handler (newVal) {
        const catalogIdRes = await getdirectorys(newVal)
        this.directoryList = catalogIdRes.data.items
      },
      deep: true
    },
    optionsList: {
      handler (newVal) {
        this.form.options = newVal
      },
      deep: true
    }
  },
  mounted () {
    this.getsubjectList()
    this.getenterpriseList()
    this.gettags()
  },
  methods: {
    // 城市--地区
    changecity () {
      this.regionList = citys(this.form.province)
    },
    // 富文本校验
    contentRule () {
      this.$refs.form.validateField('question')
    },
    // 获取所属学科列表
    async getsubjectList () {
      const res = await getsubjects()
      this.subjectList = res.data
    },
    // 获取企业列表
    async getenterpriseList () {
      const res = await getenterprise()
      this.enterpriseList = res.data.items
    },
    // tags
    async gettags () {
      const res = await list(this.data)
      this.tagsList = res.data.items
    },
    // 简选按钮
    isshowbtn () {
      this.isshow = false
    },
    // 单选按钮
    singlebtn () {
      this.isdisplay = true
      this.isshow = true
      this.isdisabled = true
    },
    // 多选按钮
    multiplebtn () {
      this.isdisplay = false
      this.isshow = true
      this.isdisabled = false
    },
    // 转换tag
    transformation () {
      this.form.tags = String(this.tagArr)
    },
    // 确认按钮
    submitForm () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          console.log(this.mallid)
          if (this.mallid) {
            await update(this.form)
            this.$message.success('修改成功')
          } else {
            await add(this.form)
            this.$message.success('添加成功')
          }
          this.$router.push({
            path: '/questions/list'
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 数据回显
    async getdetail () {
      if (this.mallid === undefined) {
        return false
      } else {
        const res = await detail({ id: this.mallid })
        this.form = res.data
        this.tagArr = res.data.tags.split(',')
        console.log(this.tagArr)
        this.gettags()
        if (this.form.questionType === '1') {
          this.fetchRadio()
        } else if (this.form.questionType === '2') {
          this.fetchChecked()
        }
      }
    },
    // 获取id
    getid () {
      this.mallid = this.$route.query.id
    },
    // 添加input框
    addformpush () {
      this.ASCIIlist = this.optionsList.map((item) => item.code)
      const a = this.ASCIIlist[this.ASCIIlist.length - 1] // 获取选项数组的追后一个选项
      const b = a.charCodeAt() + 1 // 将选项的字符转化为ascii码并且加一
      const c = String.fromCharCode(b) // 将加一后的ascii码重新转化为字符
      // this.ASCIIlist.push(c) 将转化后的字符加入数组
      this.optionsList.push({
        code: c,
        title: '',
        img: '',
        isRight: 0
      })
    },
    // 单选功能的按钮
    handleRadio () {
      this.optionsList.map((item) => {
        if (item.code === this.isChoice) {
          item.isRight = true
        }
        return item
      })
      this.form.options = this.optionsList
    },
    // 单选功能的回显
    // 要整体的optionsList结构数据，和isChoice的状态
    fetchRadio () {
      this.form.options.forEach((item) => {
        if (item.isRight === 1) {
          this.isChoice = item.code
        }
      })
      this.optionsList = this.form.options
    },
    // 多选按钮
    handleCheckedChange () {
      this.optionsList.map((item) => {
        if (this.isCheckeds.includes(item.code)) {
          item.isRight = true
        }
        return item
      })
      this.form.options = this.optionsList
    },
    // 多选选功能的回显
    // 要整体的optionsList结构数据，和isCheckeds的状态
    fetchChecked () {
      this.form.options.forEach((item) => {
        if (item.isRight === 1) {
          this.isCheckeds.push(item.code)
        }
      })
      this.optionsList = this.form.options
      this.multiplebtn()
    },
    // 设置图片
    setImg (imageUrl, code) {
      this.optionsList.forEach(item => {
        if (item.code === code) {
          item.img = imageUrl
        }
      })
    },
    // 设置多选图片
    setcheckImg (imageUrl, code) {
      this.optionsList.forEach(item => {
        if (item.code === code) {
          item.img = imageUrl
        }
      })
    }
  },
  created () {
    this.getid()
    this.getdetail()
  }
}
</script>

<style scoped lang="scss">
.el-card {
  margin: 20px;
}
// 富文本编辑器
.el-form-item::v-deep .ql-editor {
  height: 200px;
}
.el-form-item::v-deep .ql-toolbar.ql-snow {
  height: 38px;
  padding: 0px;
  padding-left: 8px;
}
// 上传图片
.option_item .avatar-uploader {
  position: relative;
  width: 100px;
  height: 60px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding-left: 22px;
  margin-left: 4px;
  display: inline-block;
  margin-bottom: 10px;
}
.avatar-uploader .el-upload {
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 14px;
  color: #303133;
  width: 100px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 60px;
  // display: block;
}
.el-icon-circle-close {
  position: absolute;
  right: 0;
  top: 0;
  -webkit-transform: translate(50%, -50%);
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
</style>
